package alarm

import (
	"github.com/gin-gonic/gin"
	"iot-base/auth/api/logic"
	"iot-base/auth/logger"
	"iot-base/auth/svc"
	types2 "iot-base/auth/types"
)

func HistoryEvent(c *gin.Context) {
	uid := c.GetInt64("uid")
	requestId, _ := c.Get("RequestId")
	resp := types2.NewResult(c)
	var req types2.ReqEventNotice
	err := c.ShouldBind(&req)
	if err != nil {
		logger.Log.Errorf("HistoryAlarm [%s] err:=%v", requestId, err)
		resp.ErrorCode(types2.ParamsError, "")
		return
	}
	isAuth := logic.NewUserLogic().CheckThingIdIsAuth(uid, req.ThingId)
	if isAuth == false {
		resp.Success(gin.H{})
		return
	}
	result := gin.H{"total": 0, "list": []interface{}{}}
	total, err := svc.Dao.TEvent.FindCount(req.ThingId, "")
	list, err := svc.Dao.TEvent.FindList(req.ThingId, "", req.Page, req.Size)
	if err != nil {
		resp.ErrorCode(types2.DBError, "")
		return
	}
	eventList := make([]types2.RespEvent, 0, len(list))
	for _, v := range list {
		temp := types2.RespEvent{
			Id:          v.UID,
			ThingId:     v.TID,
			EventID:     v.EventID,
			Time:        types2.JsonTime(v.Time),
			Level:       v.Level,
			StationName: v.StationName,
			EventName:   v.EventName,
			StationID:   v.StationID,
		}
		if v.JParams == nil {
			temp.Params = map[string]interface{}{}
		} else {
			temp.Params = v.JParams
		}
		eventList = append(eventList, temp)
	}
	result["total"] = total
	result["list"] = eventList
	resp.Success(result)
}
